import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import dayjs from 'dayjs'

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch((err) => err)
}
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
  return originalReplace.call(this, location).catch(err => err)
}


import storeOperationRoutes from './merchantOperationRoutes'

export const constantRoutes = [
  {
    path: '',
    component: () => import(/* webpackChunkName: "index" */ '@/App'),
    name: '',
    redirect: '/',
    children: [
      {
        path: '/login',
        name: 'login',
        meta: { anonymous: true },
        component: () => import(/* webpackChunkName: "login" */ '../views/login.vue'),
      },
      {
        path: '/',
        name: 'index',
        component: () => import(/* webpackChunkName: "index" */'@/views/index'),
        redirect: '/home',
        children: [
          {
            path: '/home',
            name: 'home',
            meta: {
              hiddenAside: true,
              title: "首页"
            },
            component: () => import(/* webpackChunkName: "home" */ '@/views/home.vue'),
          },
          {
            path: '/404',
            component: () => import(/* webpackChunkName: "404" */ '@/views/404'),
            hidden: true,
          },
        ],
      },
    ],
  },

  // 404 page must be placed at the end !!!
  { path: '*', redirect: '/404', hidden: true },
]

let pageRoutes = [
  ...storeManageRoutes
]




const createRouter = () =>
  new VueRouter({
    mode: 'history',
    base: '/store',
    scrollBehavior: () => ({ y: 0 }),
    // routes: constantRoutes.concat(pageRoutes),
  })

const router = createRouter()

export function resetRouter () {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

router.forceReplace = (options) => {
  if (!options.query) {
    options.query = {}
  }
  options.query.frk = new Date().valueOf()
  router.replace(options)
}
router.reload = () => {
  let options = JSON.parse(
    JSON.stringify({
      name: router.history.current.name,
      params: router.history.current.params,
      query: router.history.current.query,
    })
  )
  router.forceReplace(options)
}

/**
 *
 * 移除没有权限的菜单
 */
const removeChildren = (mapRoute, operations) => {
  let i = mapRoute.length - 1
  for (; i >= 0; i--) {
    const val = mapRoute[i]
    // 判断该路由是否需要权限显示
    if (val.hidden) {
      val.meta = {
        ...val.meta,
        hasBack: true,
      }
    }
    if (val.permission && val.permission.length) {
      // 需要权限则判断当前权限接口列表是否全在权限集合接口存在

      if (!operations.some((str) => val.permission.includes(str))) {
        mapRoute.splice(i, 1)
      } else {
        if (val.children) {
          removeChildren(val.children, operations)
        }
      }
    } else {
      if (val.children) {
        removeChildren(val.children, operations)
      }
    }
  }
  return mapRoute
}

const setRedirect = (menu, i) => {
  // 二级菜单
  const level2MenuTags = menu
  // 三级菜单
  const level3MenuTags = level2MenuTags.children
  let level3MenuIndex
  if (level2MenuTags.redirect) {
    level3MenuIndex = level3MenuTags.findIndex(
      (m3) => m3.path === level2MenuTags.redirect
    )
    if (level3MenuIndex === -1) {
      level3MenuIndex = level3MenuTags.findIndex(
        (c) => !Object.keys(c).includes('hidden')
      )
    }
  } else {
    level3MenuIndex = level3MenuTags.findIndex(
      (c) => !Object.keys(c).includes('hidden')
    )
  }
  return level3MenuIndex > -1 ? level3MenuTags[level3MenuIndex].path : ''
}
router.beforeEach(async (to, from, next) => {
  store.dispatch('app/hideSidebar', to.meta.hiddenAside ? true : false)
  if (store.state.menu.init && to.path == '/login') { // 已初始化路由并且跳转登录页面
    store.dispatch('menu/setInit', false)
    next()
    return
  } else if (to.path == '/login') { //直接跳转登录页面
    if (!router.options.routes) {
      router.options.routes = [...constantRoutes]
    } else {
      router.options.routes.push(...constantRoutes)
    }
    resetRouter()
    for (var i in constantRoutes) {
      await router.matcher.addRoute(constantRoutes[i])
    }
    next({ ...to, replace: true })
    store.dispatch('menu/setInit', true)
    return
  }
  //获取缓存token
  let Authorization = localStorage.getItem('store/Authorization') || "true"
  if (to.meta && to.meta.anonymous) {
    next()
    return
  }
  if (!Authorization) {
    sessionStorage.setItem('goto-url', location.href)
    location.href = process.env.BASE_URL + 'login'
    next()
    return
  } else {
    // let routerTopMap = await store.dispatch('menu/getAuthirizes')
    let routerTopMap = []
    const { operations } = store.state.menu

    if (!store.state.menu.init) {
      let routes = pageRoutes
      console.log('operations', operations, routes)
      removeChildren(routes, operations)
      routes = routes.map((r) => {
        if (r.children && r.children.length) {
          if (r.redirect) {
            const positionIndex = r.children.findIndex(
              (v) => v.path === r.redirect
            )
            if (positionIndex !== -1) {
              r.redirect = setRedirect(r.children[positionIndex])
            } else {
              r.redirect = setRedirect(r.children[0])
            }
          } else {
            // 没有重定向默认获取最相近的3级菜单
            r.redirect = setRedirect(
              r.children[
              r.children.findIndex((e) => e.children && e.children.length)
              ]
            )
          }
        }
        return r
      })
      let level2Routes = []
      let newRrouterMap = []
      if (!router.options.routes) {
        router.options.routes = [...newRrouterMap, ...constantRoutes, ...routes]
      } else {
        router.options.routes.push(...newRrouterMap, ...constantRoutes, ...routes)
      }

      resetRouter()
      newRrouterMap = newRrouterMap.concat(constantRoutes).concat(pageRoutes)
      for (var i in newRrouterMap) {
        await router.matcher.addRoute(newRrouterMap[i])
      }
      level2Routes = newRrouterMap
      console.log('routes', pageRoutes, newRrouterMap)
      store.dispatch('menu/setRouter', pageRoutes)
      store.dispatch('menu/setSearchRoutes', newRrouterMap)
      store.dispatch('menu/setInit', true)
      next({ ...to, replace: true })
    } else {
      next()
    }
    await store.dispatch('menu/getCurrentRoutes', { ...to })
  }

})


router.afterEach(async (to, from, next) => {
  //链接无需验证授权
  if (document.getElementById('page-loading')) document.getElementById('page-loading').remove()
  let title = await store.dispatch('app/getSystemTitle')
  if (to.meta.title) {
    document.title = `${to.meta.title}${title && '-' + title}`
  }
})

function eachRouter (mapRoute, route, resultRoute = []) {
  const newMapRoute = resultRoute
  for (const v of mapRoute) {
    if (!route.path) continue
    if (v.path === route.path.replace(/^\/store/, '')) {
      if (route.icon) v.icon = route.icon
      v.text = route.name
      newMapRoute.push(v)
      break
    } else {
      if (v.children && v.children.length) {
        eachRouter(v.children, route, newMapRoute)
      }
    }
  }
  return newMapRoute
}

export function addRouter (routes) {
  return routes
    .map((item, i) => {
      let currentRouter = {}
      currentRouter = eachRouter(pageRoutes, item)
      console.log('currentRouter', item)
      if (currentRouter.length) {
        if (item.items && item.items.length) {
          const children = addRouter(item.items)
        }
      }
      currentRouter = currentRouter[0]
      return currentRouter
    })
    .filter((v) => {
      return v
    })
}
export default router
